#include "SkipfishToolHandler.h"

// remove this
#include <wx/msgdlg.h>

#include <wx/process.h>

#include <stdio.h>


#include <iostream>

using namespace std;

SkipfishToolHandler::SkipfishToolHandler( SkipfishConfigData *config )
{
    //ctor
    this->config = config;
}

SkipfishToolHandler::~SkipfishToolHandler()
{
    //dtor

}

bool SkipfishToolHandler::ExecuteScan()
{
    // TODO Create the string and execute the scan
    wxString s = wxT("skipfish ");
    wxString aux;

    if ( this->config->username != wxT("") ) {
        s = s + wxT(" -A ") + this->config->username + wxT(":") + this->config->password;
    }

    if ( this->config->customCookie != wxT("") ) {
        s = s + wxT(" -C ") + this->config->customCookie;
    }

    if ( this->config->maxDepth > 0 ) {
        int a = this->config->maxDepth;
        aux.Printf( wxT(" -d %d "), a );
        s = s + aux;
    }

    if ( this->config->maxTotalRequest > 0 ) {
        aux.Printf( wxT(" -r %d "), (int) this->config->maxTotalRequest );
        s = s + aux;
    }

    if ( this->config->dontDescendInto5xxLocations == true ) {
        s = s + wxT(" -Z ");
    }

    if ( this->config->writeOutputTo != wxT("") ) {
        s = s + wxT(" -o ") + this->config->writeOutputTo;
    }

    if ( this->config->logWarningsAboutMixedContent == true ) {
        s = s + wxT(" -M ");
    }

    if ( this->config->loadWordlist != wxT("") ) {
        s = s + wxT(" -W ") + this->config->loadWordlist;
    }

    if ( this->config->dontLearnNewWordForTheSite == true ) {
        s = s + wxT(" -L ");
    }

    if ( this->config->dontUpdateWordlistBaseOnTheScan == true ) {
        s = s + wxT(" -V ");
    }

    if ( this->config->maxGlobalTCPConnections > 0 ) {
        aux.Printf( wxT(" -g %d "), this->config->maxGlobalTCPConnections );
        s = s + aux;
    }

    if ( this->config->maxCosecutiveHttpFails > 0 ) {
        aux.Printf( wxT(" -f %d "), this->config->maxCosecutiveHttpFails );
        s = s + aux;
    }

    if ( this->config->totalRequestTimeout > 0 ) {
        aux.Printf( wxT(" -t %d "), this->config->totalRequestTimeout );
        s = s + aux;
    }

    s += wxT( " http://localhost:3000 " );

    //wxMessageBox( s, wxT("Info") );

    //wxProcess *pr = wxProcess::Open( s, wxEXEC_SYNC);

    //wxInputStream *st = pr->GetInputStream();

    //wxString cmd_out;

    //while ( !st->Eof() ) {
    //    cmd_out += wxChar( st->GetC() );
    //}



    FILE *pf = popen( s.fn_str(), "r" );

    char buff[50];

    while ( pf != NULL ) {
        while ( fgets( buff, sizeof buff, pf ) ) {
            cout << buff;
        }
    }

    return true;
}
